/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model.dao;

import exception.DuplicateConstraintException;
import exception.RemoveConstraintException;
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.ConstraintViolationException;
import model.entidades.Vinculo;

/**
 *
 * @author helton
 */
public class VinculoDao {

    @PersistenceContext
    private EntityManager em;

    public void insert(Vinculo vinculo) throws DuplicateConstraintException {
        try {
            em.persist(vinculo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new DuplicateConstraintException("Vinculo", vinculo.getTipo());
            }
        }
    }

    public void update(Vinculo vinculo) throws DuplicateConstraintException {
        try {
            vinculo = em.merge(vinculo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new DuplicateConstraintException("Vinculo", vinculo.getTipo());
            }
        }
    }

    public void delete(Vinculo vinculo) throws RemoveConstraintException {
        try {
            vinculo = em.merge(vinculo);
            em.remove(vinculo);
            em.flush();
        } catch (Exception e) {
            if (e.getCause() instanceof ConstraintViolationException) {
                throw new RemoveConstraintException();
            }
        }
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public Vinculo findById(Object id) {
        return em.find(Vinculo.class, id);
    }

    @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
    public List<Vinculo> getAll(Long idProfis) {

        try {
            Query q = em.createQuery("from Vinculo as v WHERE v.idProfis = :profis");
            q.setParameter("profis", idProfis);
            return q.getResultList();
        } catch (Exception e) {
            System.out.println("Erro print " + e);
            return null;
        }   
    }
}
